﻿package net.wangit.framework.expression;

import net.wangit.User;
import net.wangit.context.ActionContext;
import net.wangit.util.Checker;
import net.wangit.util.StringUtil;
/**
 * 用户表达式
 * @author watson
 *
 */
public class UserExpression {

	private static final String PREFIX = "$U{";
	private static final String SUFFIX = "}";

	public UserExpression() {
	}

	public static final String resolve(ActionContext ac, String expression) {
		if (Checker.isEmpty(expression))
			return expression;
		StringBuffer result = new StringBuffer();
		String attribute;
		while ((attribute = StringUtil.find(expression, UserExpression.PREFIX,
				UserExpression.SUFFIX)) != null) {
			int index = expression.indexOf((new StringBuilder(
					UserExpression.PREFIX)).append(attribute).append(
					UserExpression.SUFFIX).toString());
			result.append(expression.substring(0, index)).append(
					getValue(ac, attribute));
			expression = expression.substring(index + attribute.length()
					+ UserExpression.PREFIX.length()
					+ UserExpression.SUFFIX.length());
		}
		result.append(expression);
		return result.toString();
	}

	private static String getValue(ActionContext ac, String attribute) {
		User user = ac.getVisitor().getUser();
		String value = user.get(attribute);
		return value != null ? value : "";
	}
}
